package com.shisan.tingshu.common.minio.config;

import com.shisan.tingshu.common.execption.ShisanException;
import com.shisan.tingshu.common.minio.service.FileUploadService;
import com.shisan.tingshu.common.minio.service.impl.FileUploadServiceImpl;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@EnableConfigurationProperties(MinioProperties.class)
// 在此注解下，只有当配置文件中 minio.enabled=true 时，才会实例化该类
@ConditionalOnProperty(prefix = "minio", value = "enable", havingValue = "true")
@Slf4j
public class MinioAutoConfiguration {

    /**
     * 定义 MinioClient bean
     */
    @Bean
    // 此处的参数前面相当于有一个 @Autowired，与下面的写法等价
    // @Autowired
    // private MinioProperties minioProperties;
    public MinioClient minioClient(MinioProperties minioProperties) {

        try {
            // 创建Minio客户端
            MinioClient minioClient = MinioClient.builder()
                    .endpoint(minioProperties.getEndpointUrl())
                    .credentials(minioProperties.getAccessKey(), minioProperties.getSecretKey())
                    .build();
            boolean found = minioClient.bucketExists(BucketExistsArgs.builder().bucket(minioProperties.getBucketName()).build());
            // 判断桶是否存在
            if (!found) {
                // 创建桶
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(minioProperties.getBucketName()).build());
            } else {
                log.info("{}桶已存在", minioProperties.getBucketName());
            }
            return minioClient;
        } catch (Exception e) {
            log.error("MinioClient初始化失败，{}", e.getMessage());
            throw new ShisanException(201, "MinioClient初始化失败");
        }
    }

    /**
     * 定义 FileUploadService bean
     */
    @Bean
    public FileUploadService fileUploadService(){
        return new FileUploadServiceImpl(); // 注意返回的是实现类的对象
    }
}